#include <utf.h> 
#include <HttpRequest.h>
#include <QueryParser.h>

#include <mw/eikappui.h>
#include <mw/apacmdln.h> 
#include <mw/apgcli.h>

#include <mw/apgtask.h>
//#include <w32std.h>

#include "wrt_iap_enabler.h"	// CIAPenabler
#include "clientservercommon.h"
#include "iapsessclient.h"

_LIT(KDelimiter, " ,");
// IAP commands below
_LIT8(KUserAndDevice, "UserAndDeviceId");
_LIT8(KProductData, "ProductData");
_LIT8(KPurchaseProduct, "PurchaseProduct");
_LIT8(KIAPCmd, "command");
_LIT8(KProductID, "productId");

CIAPenabler* CIAPenabler::NewL()
	{
	CIAPenabler* self = new (ELeave) CIAPenabler();
    CleanupStack::PushL( self );
    self->ConstructL();
    CleanupStack::Pop( self );
	return self;
	}

CIAPenabler::CIAPenabler()
	{
	}

void CIAPenabler::ConstructL()
	{
	iIAPClient = RIAPSessClient::NewL();
	User::LeaveIfError(iIAPClient->Connect());
	iWait = new(ELeave)CActiveSchedulerWait();
	}

CIAPenabler::~CIAPenabler()
	{
	delete iIAPClient;
	}

void CIAPenabler::ServiceL( MHttpRequest* req )
	{
	//Get the parameters from the request
	RQueryParser qp;
	qp.ParseL(req->GetRequest()->GetQuery());

	//Read the parameters from the query
	TPtrC8 cmd = qp.GetValue(KIAPCmd);

	RDebug::Print( _L("CIAPenabler::ServiceL command (buffer will be in the next msg) "));
    RDebug::RawPrint(cmd);

	if(cmd.CompareF(KUserAndDevice) == 0)
		{
		// getting authdigest
		HBufC8* buff = iIAPClient->getAuthDigestLC();
		TPtr8 ptr = buff->Des();
		//Respond with an error 
		req->GetResponse()->SetStatus(200);
		req->GetResponse()->SendL(ptr);
		CleanupStack::PopAndDestroy(); //buff
		}
	else if(cmd.CompareF(KProductData) == 0)
		{
		TPtrC8 productId = qp.GetValue(KProductID);
		RPointerArray<HBufC8> productData(4);
		CleanupClosePushL(productData);
		iIAPClient->getProductDataL(productId, productData);
		
		TBuf8<300> result;
//		result.Append(*productData[0]); // product name
//		result.Append(KDelimiter);
		result.Append(*productData[1]); // product long description
		result.Append(KDelimiter);
//		result.Append(*productData[2]); // product short description
//		result.Append(KDelimiter);
		result.Append(*productData[3]); // price
		
		//Respond with an error 
		req->GetResponse()->SetStatus(200);
		req->GetResponse()->SendL(result);
		
		CleanupStack::PopAndDestroy(); //productData 
		}
	else if(cmd.CompareF(KPurchaseProduct) == 0)
		{
		TPtrC8 productId = qp.GetValue(KProductID);
		HBufC8* buff = iIAPClient->purchaseProductLC(productId);
		TPtr8 ptr = buff->Des();

		req->GetResponse()->SetStatus(200);
		req->GetResponse()->SendL(ptr);
		CleanupStack::PopAndDestroy(); //buff
		}
	
	qp.Close();
	}
